using System;
using System.IO;

namespace ID3Lib
{
	/// <summary>
	/// Manage MP3 file ID3v2 tags.
	/// </summary>
	public class MP3File
	{

		/// <summary>
		/// Read the ID3v2 tag model.
		/// </summary>
		/// <param name="file">File location</param>
		public TagModel Read(string file)
		{
			Stream stream = File.Open(file,FileMode.Open,FileAccess.Read,FileShare.Read);
			TagManager frameManager = new TagManager();
			TagModel tagModel = null;
			try
			{
				tagModel = frameManager.Deserialize(stream);
			}
			finally
			{
				stream.Close();
			}
			return tagModel;
		}

		/// <summary>
		/// Write the tag model to the file.
		/// </summary>
		/// <param name="file">File location were tag will be saved</param>
		/// <param name="tagModel">Tag model beeing saved</param>
		public void Write(string file, int previousTagSize, TagModel tagModel)
		{
			Stream stream = File.Open(file,FileMode.Open,FileAccess.ReadWrite,FileShare.Read);
							
//			int tagSize;
//			//Padding and foter can't exist at the same time, I prefer padding over footer.
//			//The footer is useful when the tag won't be edited often.
//			if(tagModel.Header.Padding == true) 
//			{
//				tagModel.Header.Footer = false;
//			}
//			
//			if(tagModel.Header.Footer == true)
//			{
//				// Insert the tag size and header size twice for the hader and footer. 
//				tagSize = tagModel.Header.TagSize + tagModel.Header.HeaderSize*2; 
//			}
//			else
//			{
//				// Inset the tag size and the header size.
//				tagSize = tagModel.Header.TagSize + tagModel.Header.HeaderSize;
//			}
//			stream.Seek(tagSize,SeekOrigin.Begin);
//			MemoryStream memoryStream = new MemoryStream();
//			// serialize the frames only first to get the frames real size
//			TagManager tagManager = new TagManager();
//			tagManager.Serialize(tagModel,memoryStream);
//			
//			// 
//			if(memoryStream.Length > tagSize)
//			{
//			}
//			
			// create a temp file since the tag is written to the
			// begining of the file...
			string tempFileName = Path.GetTempFileName();

			FileStream writeStream = File.Open(tempFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);

			// write the tag values out...
			TagManager tagManager = new TagManager();
			tagManager.Serialize(tagModel,writeStream);

			//Copy mp3 stream
			const int size = 4096;
			byte[] bytes = new byte[4096];
			int numBytes;

			stream.Seek(previousTagSize, SeekOrigin.Begin);

			while((numBytes = stream.Read(bytes, 0, size)) > 0)
				writeStream.Write(bytes, 0, numBytes);
			// close both files
			writeStream.Close();
			stream.Close();

			// delete the old mp3
			File.Delete(file);
			// move the temp to the "old" filename
			File.Move(tempFileName, file);
		}
	}
}
